package com.hroze.util.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * @author ahoo
 * 会话管理
 *
 */
public class SessionManager implements HttpSessionListener,
		HttpSessionAttributeListener {
	/**
	 * 会话的用户标识，不能重复
	 */
	public static String sessionMark = "";
	/**
	 * 日志
	 */
	static Logger log = Logger.getLogger(SessionManager.class);
	/**
	 * 回话存放
	 */
	public static Map<Object, HttpSession> map = new HashMap<Object, HttpSession>();

	/**
	 * 使用id找到会话
	 * 
	 * @param id sessionId或者回话标记
	 * @return
	 */
	public static HttpSession getSessionById(String id) {
		return map.get(id);
	}

	public void sessionCreated(HttpSessionEvent arg0) {
		Object userId = StringUtils.isNotBlank(sessionMark) ? arg0.getSession()
				.getAttribute(sessionMark) : arg0.getSession().getId();
		map.put(userId, arg0.getSession());
	}

	public void sessionDestroyed(HttpSessionEvent arg0) {
		Object userId = StringUtils.isNotBlank(sessionMark) ? arg0.getSession()
				.getAttribute(sessionMark) : arg0.getSession().getId();
		if (userId != null && !"".equals(userId)) {
			map.remove(userId);
		}
	}

	public void attributeAdded(HttpSessionBindingEvent arg0) {
		Object userId = StringUtils.isNotBlank(sessionMark) ? arg0.getSession()
				.getAttribute(sessionMark) : arg0.getSession().getId();
		// 增加新属性时用户登陆
	}

	public void attributeRemoved(HttpSessionBindingEvent arg0) {
		Object userId = StringUtils.isNotBlank(sessionMark) ? arg0.getSession()
				.getAttribute(sessionMark) : arg0.getSession().getId();
	}

	public void attributeReplaced(HttpSessionBindingEvent arg0) {
		Object userId = StringUtils.isNotBlank(sessionMark) ? arg0.getSession()
				.getAttribute(sessionMark) : arg0.getSession().getId();
	}

}
